﻿using B.S.AuthCenter.Api.Write.Application.Command.Menu;
using B.S.AuthCenter.Domain;
using B.S.AuthCenter.ErrorCount;
using B.S.AuthCenter.InfrasIntructure.Interface;
using MediatR;
using System.Transactions;

namespace B.S.AuthCenter.Api.Write.Application.Handler.Menu
{
    public class DeleteMenuHandler : IRequestHandler<DeleteMenuCommand, ApiResult<int>>
    {
        IBaseRepository<MenuManageModel> menuRepo;

        public DeleteMenuHandler(IBaseRepository<MenuManageModel> menuRepo)
        {
            this.menuRepo = menuRepo;
        }

        public Task<ApiResult<int>> Handle(DeleteMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var menus=menuRepo.GetAll().Where(c => c.Id == request.Id ||c.Pid==request.Id).ToList();
            
                if (menus.Count != 1)
                {

                    int r = 0;
                    foreach (var item in menus)
                    {
                        item.IsDeleted = true;
                        r = menuRepo.Update(item).Result;
                    }
                    res.Msg = "已删除当前菜单及所有子集";
                    res.Code = ApiEnum.Ok;
                    res.Datas = r;
                    return Task.FromResult(res);
                }
                else
                {
                    var menu = menuRepo.GetAll().Where(c => c.Id == request.Id).FirstOrDefault();
                    menu.IsDeleted = true;
                    int r1 = menuRepo.Update(menu).Result;
                    res.Msg = "删除当前菜单成功";
                    res.Datas = r1;
                    res.Code = ApiEnum.Success;
                    return Task.FromResult(res);
                }
            
           
           
        }
    }
}
